from genson import SchemaNode, SchemaBuilder
from jsonschema import validate

import os, uuid, json, platform

from robot.api.deco import keyword
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
from robot.utils.asserts import assert_equal, assert_not_equal

class JsonSchemaLib(object):

    def __init__(self):
        self.workspace = "json-schema"
        self.builder = SchemaBuilder()
        self.builtIn = BuiltIn()

    @keyword('Create Schema')
    def create_schema(self, json_object):

        self.builder.add_schema({"type": "object", "properties": {}})
        self.builder.add_object(json_object)
        schema = self.builder.to_schema()
        paths = self.getPaths()

        if not os.path.exists(paths):
            logger.info("[生成Schema] 目录: {} 不存在，创建中".format(paths))
            os.makedirs(paths)
        os.chdir(paths)

        fileName = self.getFileName()
        if os.path.exists(fileName):
            logger.warn('[生成Schema] 已存在，不保存schema内容，如果是要重新生成，请删除文件: {}'.format(fileName))
            return schema

        with open(fileName, 'w') as dump_f:
            dump_f.write(json.dumps(schema))
        dump_f.close()
        
        logger.info('[生成Schema] 文件: {0}, 结果: {1}'.format(fileName, schema))
        
        return schema
    
    @keyword('Validate Schema')
    def validate_schema(self, instance):

        os.chdir(self.getPaths())
        fileName = self.getFileName()
        logger.info('[校验Schema] 读取规则文件: {0}'.format(fileName))

        with open(fileName, 'r') as load_f:
            schema = json.load(load_f)
        load_f.close()
        result = validate(instance=instance, schema=schema)
        
        assert_equal(result, None, msg="[校验Schema] 校验不通过, 错误信息: {}".format(result))
        logger.info("[校验Schema] {} 校验通过".format(fileName))
        return 
    
    def getFileName(self):
        suit_name = self.builtIn.get_variable_value("${SUITE NAME}")
        test_name = self.builtIn.get_variable_value("${TEST NAME}")

        return ''.join(str(uuid.uuid5(uuid.NAMESPACE_DNS, suit_name + test_name)).split('-')) 
    
    def getPaths(self):

        suit_name = self.builtIn.get_variable_value("${SUITE NAME}")
        test_name = self.builtIn.get_variable_value("${TEST NAME}")

        sysstr = platform.system()
        home = os.path.expanduser('~')
        if(sysstr == "Windows"):
            paths = home + "\\" + self.workspace + "\\" + str.replace(suit_name, ".", "\\")
        else:
            paths = home + "/" + self.workspace + "/" + str.replace(test_name, ".", "/")
        return paths